package com.runa.rccprotocol.analysis;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.Node;
import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.persistence.factory.gd.GdConstant;
import com.runa.persistence.service.LogService;
import com.runa.persistence.task.RequestPendingTask;
import com.runa.persistence.task.TaskTypeEnum;
import com.runa.persistence.util.LogUtil;
import com.runa.protocol.analysis.MetaBufferAnalysis;
import com.runa.protocol.analysis.ShellBufferAnalysis;
import com.runa.protocol.dto.DtuReport;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.guangda.*;
import com.runa.rccprotocol.dto.runa.RunaConcenAffirmDeny;
import com.runa.rccprotocol.dto.runa.RunaConcenResponseData;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 2024/7/2 10:42
 * zhangYB
 */
@Slf4j
public class GdAnalysis extends ShellBufferAnalysis<byte[]> {


    public GdAnalysis() {
        super(null, 0);
    }

    @Override
    public int fill(byte[] data, int length, String no) {
        log.debug("光大: {} {}", no, ByteUtil.byteToHexString(data, 0, length));
        if (length < 18) {
            return -1;
        }

        int begin;
        for (begin = 0;begin < length;begin++) {
            if ((data[begin]&0xff) == 0x68
                    && data[begin+12] == 0x68) {
                break;
            }
        }

        if (length < begin + 18) {
            return -1;
        }

        int dataLen = ByteUtil.byteToShort(data, begin + 14, ByteOrder.BA);

        if (length < begin + 18 + dataLen) {
            return -1;
        }

        byte sum = ByteUtil.sum(data, begin, 16 + dataLen);
        if (data[begin + 16 + dataLen] != sum) {
            return -1;
        }

        netEquNo = ByteUtil.bcd2str(data, begin + 1, 6, false);
        GdFmuControl c = GdFmuControl.valueOf(data[13]);
        if (null == c) {
            LogService.saveErrorLog("GD:"+netEquNo, "未知", "解析控制命令失败: {} ", ByteUtil.byteToHexString(data));
            return 0;
        }

        switch (c) {
            case HEARTBEAT:
                // 心跳
                LogUtil.linkDetect(netEquNo, "光大", data, length, "心跳");
                interData = new GdConcentratorHeartBeat(netEquNo);
                break;
            case REGISTER:
                // 注册
                LogUtil.linkDetect(netEquNo, "光大", data, length, "注册");
                interData = new GdConcentratorRegister(netEquNo);
                break;
            case READ_RESPONSE:
            case READ_ONE_RESPONSE:
                interData = analysis(data, begin, length, netEquNo);
                // 读取响应
                break;
            case VALVE_CONTROL_RESPONSE:
                LogService.saveErrorLog("GD:"+netEquNo, "控制响应", " {} ", ByteUtil.byteToHexString(data));
                interData = new RunaConcenAffirmDeny(netEquNo, true);
                break;
            case VALVE_CONTROL_RESPONSE2:
                LogService.saveErrorLog("GD:"+netEquNo, "控制响应", " {} ", ByteUtil.byteToHexString(data));
                // 68630001220100000000000068 88 1400 33349B533B738443353333B738067D6766BBFB49 9616
                byte[] controlData = ByteUtil.slice(data, begin + 16, dataLen);
                controlData = ByteUtil.byteSubByte(controlData, (byte) 0x33);
                for (int i = 0; i < controlData.length; i++) {
                    if (controlData[i] == (byte)0x68 && controlData[i+1] == (byte)0x20) {
                        interData = new RunaConcenAffirmDeny(netEquNo, true);
                        break;
                    }
                }
                break;
        }
        return 0;
    }

    public RunaConcenResponseData analysis(byte[] data, int begin, int length, String netEquNo) {
        RunaConcenResponseData response = new RunaConcenResponseData();
        response.setAddress(netEquNo);
        GdFrameSequence gdFrameSequence = new GdFrameSequence();
        byte[] bytes = ByteUtil.byteSubByte(ByteUtil.slice(data, begin + 16, length - begin - 16 - 2), (byte) 0x33);
        if (RequestPendingTask.isReadMeter(netEquNo)) {
            List<HotMeterVO> hotMeterVOS = gdFrameSequence.analysisMeter(bytes, 0, bytes.length);
            response.addRepData(hotMeterVOS.get(hotMeterVOS.size()-1));
        } else if (RequestPendingTask.isReadValve(netEquNo)) {
            String serial = null;
            RequestPendingTask task = RequestPendingTask.getTask(netEquNo);
            if (null != task) {
                Node node = task.getNode();
                if (null != node) {
                    serial = node.getSerial();
                }
            }
            List<ValveVO> valveVOS =  gdFrameSequence.analysisValve(bytes, 0, bytes.length);
            ValveVO valveVO = valveVOS.get(valveVOS.size()-1);
            if (null != serial && serial.equals("0"+valveVO.getValveSerial())) {
                valveVO.setValveSerial(serial);
            }
            response.addRepData(valveVO);
        }
        return response;
    }


    public static void main(String[] args) {
        RequestPendingTask.addTask("000117090060", new RequestPendingTask(TaskTypeEnum.READ_METER));
//        String s = "682700021901000232000000689C8C0133349B53967373C3343333B461F685676B669FA7676BBAA79C6C7D666666669B6666666692E7CF6E67CF8C66AA8C669FC76A886E888A6D8A8666BB2049333333333333349B53967373C3343333B461F685676B669FA7676BBAA79C6C7D666666669B6666666692E7CF6E67E98C66AE8C667BC76A8C6E88896D8A8666BB1D49333333333333349B53967373C3343333B461F685676B669FA7676BBAA79C6C7D666666669B6666666692E7CF6E67BD8C66988C66F7C66A8A6E88886D8A8666BB5349333333333333349B53967373C3343333B461F685676B669FA7676BBAA79C6C7D666666669B6666666692E7CF6E677E8C66DC8B66CDC66A8C6E88876D8A8666BB2E49333333333333349B53967373C3343333B461F685676B669FA7676BBAA79C6C7D666666669B6666666692E7CF6E67D88B66978B66A9C66A8C6E88866D8A";
//        String s = "6825000919010000000000006888420033339B53CA585333353333B466F685676B66EB8A776BEAEC8A777D666666669B6666666692E7F8AA67777C66E67B668F696A9FBC8797768A8666BBE68D8C66673D493216";
//        String s = "682700021901000200000000689C8C0133349B53A93963C3343333B461F685676B667A7B676B8C76CC6D7D8A6E66669B8F67FCFA92B97B6967CA7F66B88F66BFFD6ABD68887A778A8666BBE149333333333333349B53A93963C3343333B461F685676B667A7B676B6B7BCA6D7D676E66669B6B67FCFA928EFE6867BA7F66778F669BFD6ABE688879778A8666BB5E49333333333333349B53A93963C3343333B461F685676B667A7B676BDC8FC86D7DE86D66669BC666FCFA92FFE66867DE7E666C8E6677FD6ABA688878778A8666BB0249333333333333349B53A93963C3343333B461F685676B667A7B676B6AB8C66D7D796D66669BC866FCFA92B9C968679C7F66E98D66EDFC6ABF688877778A8666BB9B49333333333333349B53A93963C3343333B461F685676B667A7B676B6FBFBE6D7DAE6E66669BE7FEFBFA92BBAB6867CD7F66B68F66C9FC6ABD688876778A8666BB4849333333333333349B53A93963C3343333B461F685676B667A7B676B7EBCBC6D7DFA6D66669B69FEFBFA92AF8D68678A7F669A8E669FFC6A6769886F778A8666BB0F493333333333AE16";
        String s = "686000091701005262010000689CC60033359B53665CB383343333B461F685676B666666666B76EE966B7DD86866669BCA67676692DE8AE86797AA66FEA7669C6C6D7676696F6E6E866AC00449323232323233359B53665CB383343333B461F685676B666666666BEBBA976B7D666966669BEF69676692CFB6E86779AC66C8A966C76C6D779F6A766E6E866AC02649323232323233359B53665CB383343333B461F685676B666666666B87F7966B7D6B6866669B99FF666692988CE867CEAA66EEA8669D6C6D7E9F6A6F6E6E866AC02E4932323232329116";


        byte[] data = ByteUtil.hexStringToByte(s);
        System.out.println(data.length);
        GdAnalysis gdAnalysis = new GdAnalysis();

        int fill = gdAnalysis.fill(data, data.length, null);
        System.out.println(fill);

        IInterData gain = gdAnalysis.gain();
        System.out.println(JSON.toJSONString(gain));
    }



}
